package com.flyou.ccnucenter.ui.activity.henuBeside.note;


import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.adapter.NoteRecycleViewAdapter;
import com.flyou.ccnucenter.domain.Note;
import com.flyou.ccnucenter.domain.MyUser;
import com.flyou.ccnucenter.ui.activity.BaseActivity1;
import com.flyou.ccnucenter.utils.BmobErrorCodeUtils;
import com.flyou.ccnucenter.utils.LoginUtils;
import com.flyou.ccnucenter.widget.loading.LoadingView;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;


public class NoteListActivity extends BaseActivity1 implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private LoadingView loadingView;
    private RelativeLayout failedView;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout mSwipeLayout;
    private RelativeLayout mTitlebarRlBack;
    private TextView mTitlebarTvTitle;
    private RelativeLayout getmTitlebarRlRight;
    private ImageView title_right_imgae;
    private String userId;
    private NoteRecycleViewAdapter adapter;
    private LinearLayoutManager linearLayoutManager;

    private int currentPage = 0;
    private int pageSize = 10;
    private List<Note> noteList;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_note_list);

        loadingView = (com.flyou.ccnucenter.widget.loading.LoadingView) findViewById(R.id.loadingView);
        loadingView.setLoadingText("正在同步云端笔记，请稍后");
        loadingView.setVisibility(View.VISIBLE);

        failedView = (RelativeLayout) findViewById(R.id.failed_view);


        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);


        mTitlebarRlBack = (RelativeLayout) findViewById(R.id.titlebar_rl_back);
        mTitlebarTvTitle = (TextView) findViewById(R.id.titlebar_tv_title);
        getmTitlebarRlRight = (RelativeLayout) findViewById(R.id.titlebar_rl_Right);
        getmTitlebarRlRight.setVisibility(View.VISIBLE);
        title_right_imgae = (ImageView) findViewById(R.id.iv_right_image);
        title_right_imgae.setImageResource(R.drawable.note_add_selcetor);
        recyclerView = (RecyclerView) findViewById(R.id.recycleView);
        linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);

        //        recyclerView.addItemDecoration(new RecycleViewItemDecoration(NoteListActivity.this, RecycleViewItemDecoration.VERTICAL_LIST));

    }

    @Override
    protected void initDate() {
        mTitlebarTvTitle.setText("云笔记");
        userId = LoginUtils.getUserId(NoteListActivity.this);
        //        addNote();
        GetNoteFromNet();
    }

    /*
    *从服务器获取笔记数据
    */
    private void GetNoteFromNet() {
        MyUser myUser = new MyUser();
        BmobUser currentUser = myUser.getCurrentUser(NoteListActivity.this);
        BmobQuery<Note> query = new BmobQuery<Note>();
        query.addWhereEqualTo("userId", currentUser.getObjectId());//根据用户id查询
        query.order("-updatedAt");//根据更新时间排序
        query.setLimit(pageSize);//每页显示数据
        query.setSkip(currentPage * pageSize);//分页

        query.findObjects(this, new FindListener<Note>() {
            @Override
            public void onStart() {
                if (failedView.isShown()) {
                    failedView.setVisibility(View.GONE);
                }
                super.onStart();
            }

            @Override
            public void onFinish() {
                if (mSwipeLayout.isRefreshing()) {
                    mSwipeLayout.setRefreshing(false);
                }
                if (loadingView.isShown()) {
                    loadingView.setVisibility(View.GONE);
                }
                super.onFinish();
            }

            @Override
            public void onSuccess(List<Note> object) {

                if (currentPage == 0) {
                    noteList = object;
                    adapter = new NoteRecycleViewAdapter(NoteListActivity.this, object);
                    /*
                    * item 动画
                    * */
                    recyclerView.setItemAnimator(new SlideInLeftAnimator());
                    /*
                    * recycleview动画
                    * */

                    recyclerView.setAdapter(new ScaleInAnimationAdapter(adapter));

                    recyclerView.addOnScrollListener(new onRecycleViewScollListener());

                    adapter.setOnItemClickLitener(new onItiemClickListener());
                } else {
                    if (object.size() == 0) {

                        return;
                    }
                    noteList.addAll(object);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (currentPage == 0) {
                    failedView.setVisibility(View.VISIBLE);
                }
                Toast.makeText(NoteListActivity.this, BmobErrorCodeUtils.getMessage(code, msg), Toast.LENGTH_SHORT).show();
            }
        });

    }


    @Override
    protected void setListener() {
        mTitlebarRlBack.setOnClickListener(this);
        getmTitlebarRlRight.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.titlebar_rl_back:
                finish();
                break;
            case R.id.titlebar_rl_Right:

                Intent intent = new Intent(NoteListActivity.this, AddNoteActivity.class);
                startActivityForResult(intent, 1);

                break;

        }
    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        GetNoteFromNet();
    }

    /*
    * 滑动事件的监听
    * */
    public class onRecycleViewScollListener extends RecyclerView.OnScrollListener {
        private int lastVisibleItem = 0;
        private boolean isSlidingToLast = false;
        public onRecycleViewScollListener() {
            super();
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

            super.onScrollStateChanged(recyclerView, newState);
            if (isSlidingToLast) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                currentPage++;
                GetNoteFromNet();
            }
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (dy > 0) {
                isSlidingToLast = true;
            } else {
                isSlidingToLast = false;
            }
            lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
        }
    }

    public class onItiemClickListener implements NoteRecycleViewAdapter.OnItemClickLitener {
        @Override
        public void onItemClick(View view, int position) {
            Note note = noteList.get(position);
            Intent intent = new Intent(NoteListActivity.this, AddNoteActivity.class);
            intent.putExtra("title", note.getTitle());
            intent.putExtra("content", note.getContent());
            intent.putExtra("objectId", note.getObjectId());
            intent.putExtra("position", position);
            startActivity(intent);
        }

        @Override
        public void onItemLongClick(View view, final int position) {
            final Note notes = noteList.get(position);
            final AlertDialog.Builder alertDialog = new AlertDialog.Builder(NoteListActivity.this);
            alertDialog.setTitle("删除笔记？");
            alertDialog.setMessage("您确定删除笔记吗？");
            alertDialog.setNegativeButton("我再想想", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.setPositiveButton("必须的", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Note note = new Note();
                    note.setObjectId(notes.getObjectId());
                    note.delete(NoteListActivity.this, new DeleteListener() {
                        @Override
                        public void onSuccess() {
                            adapter.removeItem(position);
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(NoteListActivity.this, BmobErrorCodeUtils.getMessage(i, s), Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            });
            alertDialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == AddNoteActivity.ACTIVITY_UPDATE) {
                Note note = (Note) data.getSerializableExtra("note");
                int position = data.getIntExtra("position", 0);
                noteList.remove(position);
                noteList.add(0, note);
                adapter.notifyItemChanged(position);
            }
            if (resultCode == AddNoteActivity.ACTVIITY_SAVE) {
                Note note = (Note) data.getSerializableExtra("note");
                noteList.add(0, note);
                adapter.notifyItemInserted(0);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
